package net.csdra.DongPoShuZiTuShuGuan.controller;

import net.csdra.adapter.filestorage.FileStorageAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by msf on 2018/3/6.
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    FileStorageAdapter fileStorageAdapter;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public FileStorageAdapter.PutFileResponse upload(@RequestParam("file") MultipartFile multipartFile) {
        FileStorageAdapter.PutFileRequest putFileRequest = new FileStorageAdapter.PutFileRequest();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            putFileRequest.setInputStream(inputStream);
            FileStorageAdapter.PutFileResponse putFileResponse = fileStorageAdapter.putFile(putFileRequest);
            return putFileResponse;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping(value = "/{filename}", method = RequestMethod.GET)
    public Object download(@PathVariable("filename") String filename) {
        FileStorageAdapter.GetFileRequest getFileRequest = new FileStorageAdapter.GetFileRequest();
        getFileRequest.setFilename(filename);
        FileStorageAdapter.GetFileResponse getFileResponse = fileStorageAdapter.getFile(getFileRequest);

        Resource resource = new InputStreamResource(getFileResponse.getInputStream());
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setCacheControl("public,max-age=86400");
        responseHeaders.setETag("\"" + filename + "\"");
        responseHeaders.add("Cache-Control", "max-age=" + 86400);
        responseHeaders.add("Content-Length", String.valueOf(getFileResponse.getContentLength()));
        responseHeaders.add("Content-Type", getFileResponse.getContentType());
        return new ResponseEntity(resource, responseHeaders, HttpStatus.OK);
    }
}
